define(function(require, exports, module) {
    'use strict';
    var rk = require('rk');

    $.widget('rk.xsyReferContainer', $.rk.xsyDiv, {
        options: {
            onceInitNum: 3 //初次只初始化三个
        },
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._super();
            elem.removeAttr('is-private');
            elem.addClass('xsy_designer_draggable')
        },
        _init: function() {
            var me = this;
            if (me.isEditMode()) {
                me._init1();
            } else {
                me._init2();
            }
        },
        _init1: function() {
            var me = this;
            me._initChildren();
        },
        _init2: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            //window.setTimeout(function(){
            me._updateCrumbs();
            //}, 10);
            me._listenOuterEvent('onReferWidthData', function(info) {
                var wid = info.__fromUid;
                elem.find('.xsy_bus_crumbs:first a[of="' + wid + '"] span').html('(' + info.dataCount + ')').addClass('color');
            });
            me._listenOuterEvent('onReferWidthoutData', function(info) {
                var wid = info.__fromUid;
                elem.find('.xsy_bus_crumbs:first a[of="' + wid + '"] span').html('(' + 0 + ')');
            });
            me._listenOuterEvent('onReferInited', function(info) {
                var referel = $('#' + info.id);
                referel.data('data-init-finish', true);
                referel.removeAttr('refer-initing');

                if (elem.find('[refer-initing="true"]').size() === 0) {
                    me._initChildren();
                    if (me.jumpToId) me.jumpTo(me.jumpToId);
                }
            });
            $(window).on('resize', function() {
                if (rk.dataMgr.firstLoadIsDone()) {
                    me._initChildren()
                }
            })
            elem.on('click', '.xsy_bus_crumbs a', function() {
                var a = $(this);
                var id = a.attr('of');
                var queue = [];
                if (!rk.formMgr.isInited(id)) {
                    elem.find('[wtype$="Refer"]').each(function() {
                        var el = $(this);
                        var wid = el.attr('id');
                        queue.push(wid);
                        if (wid == id) return false; //break;
                    });
                    me._initChildren(queue);
                    me.jumpToId = id;
                } else {
                    // me._adjustAnchorPosition();
                }
            });
        },
        jumpToId: null,
        jumpTo: function(wid) {
            var me = this;
            var elem = me.element;
            // var href = window.location.href;
            // href = href.replace(/#[\d]+/ig, '');
            // window.setTimeout(function() {
            //     window.location.href = href + '#' + wid;
            //     
            // }, 0)
            this._delay(function() {
                location.hash = '';
                location.hash = me.jumpToId;
                // me._adjustAnchorPosition();
                me.jumpToId = null;
            }, 0);
        },
        _adjustTimer: null,
        // _adjustAnchorPosition: function() {
        //     var me = this;
        //     var elem = me.element;
        //     //if(!$('[data-layout="detail-header"]').hasClass('xsy_su_header_fold'))return;
        //     // window.clearTimeout(me._adjustTimer);
        //     // me._adjustTimer = window.setTimeout(function() {
        //     //     var dhead = $('[ data-layout="head"]');
        //     //     var sp = elem.scrollParent(),
        //     //         st = sp.scrollTop(),
        //     //         offset = (dhead.hasClass('xsy_su_header_fold') || dhead.hasClass('xsy_su_header_fold_menu_fold') ? 90 : 220) + 2;
        //     //     sp.scrollTop(st - offset);
        //     // }, 100);
        // },
        _updateCrumbs: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var NUM_OF_SHOW = 4;

            var refers = elem.find('[wtype$="Refer"]');
            var crumbs = elem.find('.xsy_bus_crumbs:first');
            var crumbHtmls = [];
            refers.each(function() {
                var uid = $(this).attr('id');
                var title = $(this).runMethod('getTitle');
                var amount = $(this).runMethod('getAmount');
                var wtype = $(this).attr('wtype')
                var noInit = me._noInit(uid);
                if (noInit) return true;

                crumbHtmls.push('<a href="#' + uid + '" of="' + uid + '"><span>加载中</span></a>');

                rk.dataMgr.loadData(uid, {
                    noLoadList: true,
                    detailId: me._getDetailId(),
                    groupId: me._getGroupId(),
                    belongId: me._getBelongId()
                }, function(result) {
                    var name = result.self.name ? result.self.name : '{{name}}';
                    var crumbs = elem.find('.xsy_bus_crumbs:first');
                    if(crumbs.find('a[of]').size() >= NUM_OF_SHOW)crumbs.show();
                    var color = result.self.dataCount && result.self.dataCount > 0 ? 'color' : '';
                    elem.find('.xsy_bus_crumbs:first a[of="' + result.uuid + '"]').css('visibility', 'visible').html(rk.i18n(name) + ' <span class=' + color + '>(' + (result.self.dataCount ? result.self.dataCount : 0) + ')</span>');
                    elem.find('.xsy_listpreview:first').find('.crumbsloading:first').remove();
                });
            });
            elem.find('.xsy_listpreview:first').prepend('<div class="xsy_bus_crumbs" style="display:none;">' + (crumbHtmls.length < NUM_OF_SHOW ? '' : crumbHtmls.join('')) + '</div>');
        },
        initingIdList: {},
        _initChildren: function(forceQueue) {
            var me = this;
            if (me.isEditMode()) {
                me._super();
            } else {
                me._initChildren2(forceQueue);
            }
        },
        _initChildren2: function(forceQueue) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var initQueue = [];
            var isForce = false;
            if (typeof forceQueue == 'undefined') {
                elem.find('[wtype$="Refer"]').each(function() {
                    var el = $(this);
                    var wid = el.attr('id');
                    var noInit = me._noInit(wid);
                    if (!noInit) {
                        var wtype = el.attr('wtype');
                        if (initQueue.length < opt.onceInitNum && !rk.formMgr.isInited(wid)) initQueue.push(wid);
                    }
                });
            } else {
                initQueue = forceQueue;
                isForce = true;
            }
            for (var i = 0; i < initQueue.length; i++) {
                var wid = initQueue[i];
                me.initingIdList[wid] = wid; //记录正在初始化的控件
                var wel = $('#' + wid);
                wel._force_init = isForce;
                wel.attr('refer-initing', 'true');
                rk.formMgr.createWidget(wel);
            }
        },
        _noInit: function(wid) {
            var info = rk.formMgr.getWidgetInfo(wid);
            var noInit = false;
            if (info && info.userPermission && info.userPermission.l === 0) {
                noInit = true;
            }
            return noInit;
        }
    });
});
